package com.unswift.window.factory;

import java.awt.Dimension;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import com.unswift.QuickApplication;
import com.unswift.constant.QuickConstant;
import com.unswift.utils.ObjectUtils;
import com.unswift.window.extend.Attribute;

public final class FileChooseFactory {

	/**
	 * 创建文件选择器并返回选中的文件
	 * @param attribute
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T create(Attribute attribute){
		JFileChooser fileChoose=attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_DEFAULT_FILEPATH)?new JFileChooser((File)attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_DEFAULT_FILEPATH)):new JFileChooser();
		if(attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_TYPE)){
			fileChoose.setFileSelectionMode(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_TYPE));
		}else{
			fileChoose.setFileSelectionMode(JFileChooser.FILES_ONLY);
		}
		fileChoose.setPreferredSize(new Dimension(900, 400));
		boolean multiSelectionEnabled=true;
		if(attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_MULTISELECTION_ENABLED)){
			multiSelectionEnabled=attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_MULTISELECTION_ENABLED);
			fileChoose.setMultiSelectionEnabled(multiSelectionEnabled);
		}
		if(attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_ENABLED)){
			fileChoose.setEnabled(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_ENABLED));
		}
		if(attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_DEFAULT_FILENAME)){
			fileChoose.setSelectedFile(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_DEFAULT_FILENAME));
		}
		if(attribute.exists(Attribute.ATTRIBUTE_FILECHOOSE_FILTER)){
			fileChoose.addChoosableFileFilter(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_FILTER));
			fileChoose.setFileFilter(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_FILTER));
		}
		int status=fileChoose.showOpenDialog(attribute.get(Attribute.ATTRIBUTE_FILECHOOSE_DEPEND));
		if (status == JFileChooser.APPROVE_OPTION) {
			if(multiSelectionEnabled){
				return (T)fileChoose.getSelectedFiles();
			}else{
				return (T)fileChoose.getSelectedFile();
			}
		}
		return null;
	}
	
	/**
	 * 
	 * @param suffix .sql等
	 * @param comment sql文件(*.sql)等
	 * @return
	 */
	public static FileFilter createFilter(String suffix, String comment){
		FileFilter filter=new FileFilter() {
			@Override
			public String getDescription() {
				return comment;
			}
			@Override
			public boolean accept(File f) {
				if (f.getName().endsWith(suffix) || f.isDirectory()) {
					return true;
				}
				return false;
			}
		};
		return filter;
	}
	
	public static File getDefaultFile(){
		String defaultPath=QuickApplication.getConfig(QuickConstant.CONF_FILE_CHOOSE_OPEN_PATH);
		if(ObjectUtils.isEmpty(defaultPath)){
			defaultPath=System.getenv().get(QuickConstant.WINDOW_SYSTEM_USERPROFILE);
		}
		return new File(defaultPath);
	}
}
